package org.alex.sample.service.Impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.alex.sample.VO.UserVO;
import org.alex.sample.dao.IUserDAO;
import org.alex.sample.model.ExamUserRole;
import org.alex.sample.model.User;
import org.alex.sample.page.PagerModel;
import org.alex.sample.service.IUserService;
import org.alex.sample.utils.ExcelUtils;
import org.alex.sample.utils.MD5;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


@Service
public class IUserServiceImpl implements IUserService {
	
	@Autowired
	private IUserDAO userDao;

	@Override
	public List<UserVO> findAllUsers() throws Exception {
		List<User> userList = userDao.findAllUser();
		List<UserVO> userVOList = new ArrayList<UserVO>();
		for(User user:userList) {
			user.setGender(user.getGender().equals("0")?"男":"女");
			UserVO userVO = new UserVO();
			BeanUtils.copyProperties(user, userVO);
			for(ExamUserRole examUserRole:user.getExamUserRole()) {
				userVO.setRoleName(examUserRole.getExamRole().getName());
				userVO.setRoleId(examUserRole.getExamRole().getRoleId());
			}
			userVOList.add(userVO);
		}
		return userVOList;
	}
	
	@Override
	public void createUser(User user) throws Exception{
		user.setPassword(MD5.getMD5Code(user.getPassword()));
		user.setGender("男".equals(user.getGender())?"0":"1");
		userDao.createUser(user);
	}

	@Override
	public User findUserById(Integer id) throws Exception {
		User user = userDao.findUserById(id);
		user.setGender(user.getGender().equals("0")?"男":"女");
		return user;
	}

	@Override
	public void editUser(User user) throws Exception {
		user.setPassword(MD5.getMD5Code(user.getPassword()));
		user.setGender("男".equals(user.getGender())?"0":"1");
		userDao.editUser(user);
	}

	@Override
	public void deleteUser(Integer id) throws Exception {
		userDao.deleteUser(id);
	}

	@Override
	public void saveStudentByExcel(InputStream inputStream, String postfix) throws Exception {
		Workbook wk = ExcelUtils.openWorkbook(inputStream, postfix);
		List<User> userList = ExcelUtils.getStudentListByExcel(wk);
		userDao.saveStudentByExcel(userList);
	}
	
	public PagerModel<UserVO> findAllByPage() throws Exception{
		return userDao.findAllByPage();
	}

	@Override
	public void deleteMoreUser(int[] idArr) throws Exception {
		userDao.deleteMoreUser(idArr);
	}

}
